package com.blue.base.common.utils.http;

import com.blue.base.common.bean.resp.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * @author liulei
 * @version 1.0
 */
public class ResponseUtil {
    private ResponseUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 通过流写到前端
     *
     * @param objectMapper 对象序列化
     * @param response     response
     * @param msg          返回信息
     * @param httpStatus   返回状态码
     * @throws IOException
     */
    public static void responseStream(ObjectMapper objectMapper, HttpServletResponse response, String msg, int httpStatus) throws IOException {
        JsonResult result = JsonResult.define(httpStatus, msg);
        responseWrite(objectMapper, response, result);
    }

    /**
     * 通过流写到前端
     *
     * @param objectMapper 对象序列化
     */
    public static void responseSucceed(ObjectMapper objectMapper, HttpServletResponse response, Object obj) throws IOException {
        JsonResult result = JsonResult.ok(obj);
        responseWrite(objectMapper, response, result);
    }

    /**
     * 通过流写到前端
     */
    public static void responseFailed(ObjectMapper objectMapper, HttpServletResponse response, String msg) throws IOException {
        JsonResult result = JsonResult.failed(msg);
        responseWrite(objectMapper, response, result);
    }

    private static void responseWrite(ObjectMapper objectMapper, HttpServletResponse response, JsonResult result) throws IOException {
        response.setContentType("application/json");
        try (
                Writer writer = response.getWriter();
        ) {
            writer.write(objectMapper.writeValueAsString(result));
            writer.flush();
        }
    }
}
